/**
 * Created by 小敏哥on 2017/3/8.
 */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Toast, Popup} from 'antd-mobile';
import AlipayJSOperation from '../../utils/alipayJSOperation';
import style from './yearlyCheckDetail.scss';
import {checkInspection} from '../../actions/homeAction';
import ItemList from '../../components/common/itemList';
import CarDetail from '../../components/calculatorOfYearlyCheck/carDetail';
import {MeansureAgain} from '../../components/Home';
import SendCxytjMessage from '../../utils/sendCxytjMessage';
import typeOfBrowser from '../../utils/typeOfBrowser';
import urlOperation from '../../utils/urlOperation';
import common from '../../utils/common';
import ReModal from '../../components/common/reModal';
import NotYetTips from '../../components/calculatorOfYearlyCheck/notYetTips';
import BackMeanSure from '../../utils/backMeanSure';
import {getCarViewInfo,updateMessage} from '../../actions/calculatorAction';
import PageBar from '../../components/common/pageBar';

class YearlyCheckDetail extends Component {
    constructor(props) {
        super(props);
        this.checkInspection = this.checkInspection.bind(this);
        this.goToComfirmOrder = this.goToComfirmOrder.bind(this);
        this.goBackToCalculator = this.goBackToCalculator.bind(this);
       // this.backMeanSureInstance = new BackMeanSure(this.goHome.bind(this), 'yearlyCheckDetail');
    }


    //当获取不到所需数据时直接定位到首页，由于首页做了一些兼容，不带userId
    dataEmptyErrorOperation() {
        if (!this.props.carNumber) {
            location.replace(`${location.href.split('?')[0].split('#')[0]}#/?userId=${localStorage.getItem('userId')}&detailUserType=${localStorage.getItem('detailUserType')}`);
        }
    }

    //检查车辆是否支持年检代办
    checkInspection(callBack) {
        this.props.dispatch(checkInspection({carNumber: this.props.carNumber, carId: this.props.carId}, (result) => {
            callBack(result);
        }))
    }

    //返回计算器
    goBackToCalculator() {
        //此页面有两个入口，分别是年检计算器和更新页面，根据不同页面传进来不同的参数确定返回计算的页面
        if (this.props.params.type == 'update') {
            this.context.router.replace(`/updateCarInfo/${this.props.carNumber}/${this.props.carId}`);
        }
        else {
            this.context.router.replace(`/calculatorOfYearlyCheck/${this.props.carNumber}/${this.props.carId}`);
        }

        SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_CheckRecalculate'});
    }

    //返回首页
    goHome(back, stay, toUrl) {
      /*  if (typeOfBrowser.getChannelOfBrowser() == 'app') {
            //app直接关闭当前webview回到年检提醒
            common.closeAppView();
        }
        else {*/
            /*history.pushState({}, '', '');
            let backNumber = -1 * history.length + 1;
            history.go(backNumber);*/
       // }
        history.back();
    }


    //弹出定位提示
    showMeansure(continueCallBack) {
        let attrs = {
            city: this.props.position,
            cancel: () => {
                Popup.hide();
            },
            continue: () => {
                Popup.hide();
                continueCallBack();
            }
        };
        Popup.show(<MeansureAgain {...attrs}/>, {animationType: 'slide-up'});
    }

    //构建跳转地址
    getInspectionUrl(bizFlag) {
        let url = '';
        if (typeOfBrowser.getChannelOfBrowser() == 'app'&&(sessionStorage.getItem('projectType')=='remind')) {
            let finalUrl = encodeURIComponent(`/confirmOrder/${this.props.carId}/${encodeURIComponent(this.props.carNumber)}`);
            url = `remindProcessDetail/${finalUrl}/${bizFlag}`;
        }
        else {
            url = `/confirmOrder/${this.props.carId}/${encodeURIComponent(this.props.carNumber)}/${bizFlag}`;
        }
        return url;
    }


    toUrlByOpenNewView(url) {
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1&&(sessionStorage.getItem('projectType')=='remind')) {
            //此处增加app用于识别年检提醒
            let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&appType=remind/#${url}`;
            common.openNewBrowserWithURL(finalUrl);
        }
        else {
            this.context.router.push(url);
        }
    }

    //去往订单确认页
    goToComfirmOrder() {
        //首先根据后端返回的状态判断
        if (this.props.canCheck) {
            this.checkInspection((result) => {
                if (result.bizFlag == '1' || result.bizFlag == '2') {
                    //粤牌车检测到过线检时弹框提示
                    if (result.msg) {
                        ReModal.confirm(result.msg, () => {
                            SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_popup_ClickHandle'});
                            this.toUrlByOpenNewView(this.getInspectionUrl(result.bizFlag));
                        },()=>{
                            SendCxytjMessage.sendMessage({
                                eventId: 'H5_E_Interspection_messagepage_popup_ClickCancer'
                            });
                        },{okText:'前往办理'});
                        return;
                    }

                    //7,9,10,10这几种状态监测到定位不在广州时弹出二次确认框
                   /* if (this.props.position && this.props.position.indexOf('广州') < 0 && (result.state == 7 || result.state == 9 || result.state == 10 || result.state == 11)) {
                        this.showMeansure(() => {
                            this.toUrlByOpenNewView(this.getInspectionUrl(result.bizFlag));
                        })
                    }
                    else {*/
                        //正常套路
                        this.toUrlByOpenNewView(this.getInspectionUrl(result.bizFlag));
                   // }
                }
                else {
                    if(result.state==0){
                        //未进入年检周期时做特殊弹窗处理
                        if(result.registerDate&&result.checkDate){
                            ReModal.showOnlyComponent(<NotYetTips registerDate={result.registerDate} expiryDate={result.checkDate} close={()=>{
                                ReModal.close();
                                SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_popup_ClickCancer'});
                            }} updateCallback={()=>{
                                ReModal.close();
                                this.updateMessage();
                                SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_popup_Updatetime'});
                            }}/>);
                        }
                        else{
                            ReModal.confirm(result.msg,()=>{
                                SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_popup_Recalculate'});
                                this.goBackToCalculator();
                            },()=>{
                                SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_popup_ClickCancer'});
                            },{okText:'重新计算'})
                        }
                    }
                    else{
                        ReModal.alert(result.msg);
                    }
                }
            })
        }
        SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_ClickHandle'});
    }


    componentWillMount() {
        // this.dataEmptyErrorOperation();
    }

    componentDidMount() {
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        AlipayJSOperation.setTitle('年检信息');
        AlipayJSOperation.setBarColor('#2FB3FE');
        document.querySelector("title").innerHTML = "年检信息";
        SendCxytjMessage.sendMessage({eventId: 'H5_P_Interspection_Entermessagepage'});
        //此处兼容ios的一个bug，顶层会有一个蒙层挡住页面，强制重新渲染
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            common.setViewTitle('年检信息');
        }
        this.props.dispatch(getCarViewInfo({
            carId: this.props.params.carId,
            carNumber: this.props.params.carNumber,
        }));
        //this.backMeanSureInstance.bindBackMeansure();
    }

    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }

    getTipsIcon() {
        if (this.props.bizFlag == '1' || this.props.bizFlag == '2') {
            return <img src="./images/warn-gray.png" onClick={ () => {
                this.toUrlByOpenNewView(`/inspectionTips/${this.props.bizFlag}`);
            }}/>;
        }
        return '';
    }

    updateMessage(){
        this.props.dispatch(updateMessage({
            carId: this.props.params.carId,
            carNumber: this.props.params.carNumber,
            registerDate: this.props.registerDate,},()=>{
            this.props.dispatch(getCarViewInfo({
                carId: this.props.params.carId,
                carNumber: this.props.params.carNumber,
            }))
        }))
    }

    //已办过年检更新信息
    updateMessageConfirm(){
        ReModal.confirm('确定已办理过本次年检？确认后将为您重新计算年检时间。',()=>{
            this.updateMessage();
        })
        SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_messagepage_Clickupdate'});
    }

    render() {
        let isRemind=sessionStorage.getItem('projectType')=='remind';
        let fontStyle = {
            color: this.props.color
        };
        const bizFlag_n=this.props.bizFlag=='1'?'6年免检':this.props.bizFlag=='2'?'上线检测':''
        return <div className={style.container}>
            {!isRemind?<PageBar title="年检信息"/>:''}
            <div className={style.listContainer}>
                <ItemList borderPaddingLeft="15px" borderPaddingRight="15px">
                    <div className={style.firstDetailHeaderItem}>
                        <div>
                            <div className={style.carNumber}>{this.props.carNumber}</div>
                            <div className={style.inspectionType}><span>{bizFlag_n}</span>{this.getTipsIcon()}
                            </div>
                        </div>
                        <div>
                            <div>
                                <img src={this.props.imgUrl}/>
                                <span style={fontStyle}>{this.props.description}</span>
                            </div>
                            <div className={style.littleTips}>{this.props.littleTips}</div>
                        </div>
                    </div>
                    <div className={style.secondDetailHeaderItem}>
                        {this.props.statusMsg}
                    </div>
                </ItemList>
            </div>
            <div className={style.detailContainer}>
                <CarDetail registerDate={this.props.registerDate} expiryDate={this.props.expiryDate}
                           daysText={this.props.daysText} days={this.props.days} reCalculate={this.goBackToCalculator} status={this.props.status}/>
            </div>
            <div className={style.buttonContainer}>
                <button className={ style.back} onClick={this.goHome}>返回 </button>
                <button className={this.props.canCheck ? style.go : style.unable} onClick={this.goToComfirmOrder}>立即办理 </button>
            </div>
            {this.props.status!=0?<div className={style.bottomTips}><span>已办过本次年检？</span><a onClick={this.updateMessageConfirm.bind(this)}>点击更新信息</a></div>:''}
        </div>
    }
}

//react router跳转时使用了context，此处需要显式声明
YearlyCheckDetail.contextTypes = {
    router: React.PropTypes.object.isRequired
};

function mapStateToProps(state) {
    console.log(state);
    return Object.assign({}, state.calculatorInfo.yearlyCheckInfo, {
        position: state.homeInfo.position,
    });
}


export default connect(mapStateToProps)(YearlyCheckDetail)